<template>
  <div class="container">
    <div class="app-container">
      <el-button class="btn-add" size="mini" type="primary" @click="openshowDialog(1,0)">添加权限</el-button>
      <el-table :data="list" row-key="id" default-expand-all>
        <el-table-column label="名称" prop="name" />
        <el-table-column label="标识" prop="code" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="操作">
          <template slot-scope="{row}">
            <el-button v-if="row.type === 1" size="mini" type="text" @click="openshowDialog(2,row.id)">添加</el-button>
            <el-button size="mini" type="text" @click="$refs.addPermission.editRow(row.id)">编辑</el-button>
            <el-popconfirm title="确定删除吗？" @onConfirm="delRow(row.id)">
              <el-button slot="reference" size="mini" type="text">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 弹框 -->
    <add-permission ref="addPermission" @updateList="initData" />
  </div>
</template>
<script>
import { deletePermissionApi, getPermissionListApi } from '@/api/permission'
import { transListToTreeData } from '@/utils'
import addPermission from './components/addPermission.vue'
export default {
  name: 'Permission',
  components: { addPermission },
  data() {
    return {
      // 列表数据
      list: []
    }
  },
  created() {
    // 调用
    this.initData()
  },
  methods: {
    // 初始化数据列表
    async initData() {
      // 发送请求
      const res = await getPermissionListApi()
      // console.log(res)
      // 使用工具函数转化成树形结构
      this.list = transListToTreeData(res, 0)
    },
    // 打开弹框
    openshowDialog(type, pid) {
      // type是权限类型  1是页面权限，2是按钮权限
      // pid是父级，0标识的是一级菜单，其他就是父级的id
      this.$refs.addPermission.formData.type = type
      this.$refs.addPermission.formData.pid = pid
      this.$refs.addPermission.showDialog = true
    },
    // 删除
    async delRow(id) {
      // 发送请求
      await deletePermissionApi(id)
      // 提示成功
      this.$message.success('删除成功')
      // 重新拉取数据
      this.initData()
    }
  }
}
</script>
<style>
.btn-add {
  margin: 10px;
}
</style>
